<template>
  <div class="login-container flex-center">
    <div class="login-box">
      <h2 class="login-title">微服务开发平台</h2>
      
      <!-- 登录方式选项卡 -->
      <el-tabs v-model="activeTab" class="login-tabs">
        <el-tab-pane label="账号密码登录" name="account">
          <el-form ref="accountFormRef" :model="accountForm" :rules="accountRules" class="login-form">
            <el-form-item prop="userName">
              <el-input v-model="accountForm.userName" placeholder="请输入用户名" prefix-icon="el-icon-user">
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input v-model="accountForm.password" type="password" placeholder="请输入密码" show-password>
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item prop="captcha">
              <div class="captcha-container">
                <el-input v-model="accountForm.captcha" placeholder="请输入验证码">
                  <template #prefix>
                    <el-icon><Picture /></el-icon>
                  </template>
                </el-input>
                <img class="captcha-img" :src="captchaUrl" @click="refreshCaptcha" alt="验证码" />
              </div>
            </el-form-item>
            
            <el-button type="primary" class="login-btn" :loading="loading" @click="handleAccountLogin">
              登录
            </el-button>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="手机号登录" name="phone">
          <el-form ref="phoneFormRef" :model="phoneForm" :rules="phoneRules" class="login-form">
            <el-form-item prop="phoneNumber">
              <el-input v-model="phoneForm.phoneNumber" placeholder="请输入手机号">
                <template #prefix>
                  <el-icon><Iphone /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item prop="captchaImage">
              <div class="captcha-container">
                <el-input v-model="phoneForm.captchaImage" placeholder="请输入图形验证码">
                  <template #prefix>
                    <el-icon><Picture /></el-icon>
                  </template>
                </el-input>
                <img class="captcha-img" :src="phoneCaptchaUrl" @click="refreshPhoneCaptcha" alt="验证码" />
              </div>
            </el-form-item>
            
            <el-form-item prop="captcha">
              <div class="captcha-container">
                <el-input v-model="phoneForm.captcha" placeholder="请输入短信验证码">
                  <template #prefix>
                    <el-icon><Message /></el-icon>
                  </template>
                </el-input>
                <el-button 
                  type="primary" 
                  :disabled="smsCodeTimer > 0" 
                  @click="handleSendSmsCode"
                >
                  {{ smsCodeTimer > 0 ? `${smsCodeTimer}秒后重新获取` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
            
            <el-button type="primary" class="login-btn" :loading="loading" @click="handlePhoneLogin">
              登录
            </el-button>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="邮箱登录" name="email">
          <el-form ref="emailFormRef" :model="emailForm" :rules="emailRules" class="login-form">
            <el-form-item prop="email">
              <el-input v-model="emailForm.email" placeholder="请输入邮箱">
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item prop="captchaImage">
              <div class="captcha-container">
                <el-input v-model="emailForm.captchaImage" placeholder="请输入图形验证码">
                  <template #prefix>
                    <el-icon><Picture /></el-icon>
                  </template>
                </el-input>
                <img class="captcha-img" :src="emailCaptchaUrl" @click="refreshEmailCaptcha" alt="验证码" />
              </div>
            </el-form-item>
            
            <el-form-item prop="captcha">
              <div class="captcha-container">
                <el-input v-model="emailForm.captcha" placeholder="请输入邮箱验证码">
                  <template #prefix>
                    <el-icon><Key /></el-icon>
                  </template>
                </el-input>
                <el-button 
                  type="primary" 
                  :disabled="emailCodeTimer > 0" 
                  @click="handleSendEmailCode"
                >
                  {{ emailCodeTimer > 0 ? `${emailCodeTimer}秒后重新获取` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
            
            <el-button type="primary" class="login-btn" :loading="loading" @click="handleEmailLogin">
              登录
            </el-button>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      
      <div class="login-footer">
        <p>Copyright © 2025 icoolkj 微服务开发平台</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Picture, Iphone, Message, Key } from '@element-plus/icons-vue'
import { loginByUsername, loginByPhone, loginByEmail, getCaptcha, getSmsCode, getEmailCode } from '@/api/auth'
import { useUserStore } from '@/store/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 当前激活的选项卡
const activeTab = ref('account')

// 加载状态
const loading = ref(false)

// 验证码图片URL
const captchaUrl = ref('')
const phoneCaptchaUrl = ref('')
const emailCaptchaUrl = ref('')

// UUID
const accountUuid = ref('')
const phoneUuid = ref('')
const emailUuid = ref('')

// 短信验证码UUID
const smsUuid = ref('')
// 邮箱验证码UUID
const emailCodeUuid = ref('')

// 账号密码登录表单
const accountFormRef = ref(null)
const accountForm = reactive({
  userName: '',
  password: '',
  captcha: '',
  uuid: ''
})

// 手机号登录表单
const phoneFormRef = ref(null)
const phoneForm = reactive({
  phoneNumber: '',
  captchaImage: '',
  captcha: '',
  uuid: ''
})

// 邮箱登录表单
const emailFormRef = ref(null)
const emailForm = reactive({
  email: '',
  captchaImage: '',
  captcha: '',
  uuid: ''
})

// 短信验证码倒计时
const smsCodeTimer = ref(0)
let smsTimerInterval = null

// 邮箱验证码倒计时
const emailCodeTimer = ref(0)
let emailTimerInterval = null

// 表单验证规则
const accountRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

const phoneRules = {
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  captchaImage: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入短信验证码', trigger: 'blur' }
  ]
}

const emailRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  captchaImage: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入邮箱验证码', trigger: 'blur' }
  ]
}


// 获取图形验证码
const fetchCaptcha = async (type = 'account') => {
  try {
    console.log(`正在获取验证码 - 类型: ${type}`)
    const response = await getCaptcha()
    console.log('验证码获取成功:', response)
    
    if (!response.data || !response.data.img) {
      console.error('验证码数据格式错误:', response)
      ElMessage.error('验证码数据格式错误，使用模拟验证码')
      return
    }
    
    // 根据类型设置不同的验证码
    if (type === 'account') {
      captchaUrl.value = 'data:image/png;base64,' + response.data.img
      accountUuid.value = response.data.uuid
      accountForm.uuid = accountUuid.value
      console.log(`账号登录验证码设置成功 - UUID: ${accountUuid.value}`)
    } else if (type === 'phone') {
      phoneCaptchaUrl.value = 'data:image/png;base64,' + response.data.img
      phoneUuid.value = response.data.uuid
      phoneForm.uuid = phoneUuid.value
      console.log(`手机登录验证码设置成功 - UUID: ${phoneUuid.value}`)
    } else if (type === 'email') {
      emailCaptchaUrl.value = 'data:image/png;base64,' + response.data.img
      emailUuid.value = response.data.uuid
      emailForm.uuid = emailUuid.value
      console.log(`邮箱登录验证码设置成功 - UUID: ${emailUuid.value}`)
    }
  } catch (error) {
    console.error('获取验证码失败', error.response || error)
    ElMessage.error('获取验证码失败，使用模拟验证码')
  }
}

// 刷新账号登录验证码
const refreshCaptcha = () => {
  fetchCaptcha('account')
}

// 刷新手机登录验证码
const refreshPhoneCaptcha = () => {
  fetchCaptcha('phone')
}

// 刷新邮箱登录验证码
const refreshEmailCaptcha = () => {
  fetchCaptcha('email')
}

// 发送短信验证码
const handleSendSmsCode = async () => {
  try {
    // 验证手机号和图形验证码
    await phoneFormRef.value.validateField(['phoneNumber', 'captchaImage'])
    
    try {
      console.log('发送短信验证码请求:', {
        phoneNumber: phoneForm.phoneNumber,
        captcha: phoneForm.captchaImage,
        uuid: phoneUuid.value
      })
      
      // 发送短信验证码
      const res = await getSmsCode({
        phoneNumber: phoneForm.phoneNumber,
        captcha: phoneForm.captchaImage,
        uuid: phoneUuid.value
      })
      
      console.log('短信验证码发送成功:', res)
      
      // 保存短信验证码UUID
      smsUuid.value = res.data.uuid || ''
      console.log('短信验证码UUID:', smsUuid.value)
      
      // 开始倒计时
      smsCodeTimer.value = 60
      smsTimerInterval = setInterval(() => {
        smsCodeTimer.value--
        if (smsCodeTimer.value <= 0) {
          clearInterval(smsTimerInterval)
        }
      }, 1000)
      
      ElMessage.success('验证码已发送，请注意查收')
    } catch (error) {
      console.error('验证码发送失败', error.response || error)
      ElMessage.error(error.message || '图形验证码错误或发送失败，请重试')
      refreshPhoneCaptcha()
    }
  } catch (error) {
    console.error(error)
  }
}

// 发送邮箱验证码
const handleSendEmailCode = async () => {
  try {
    // 验证邮箱和图形验证码
    await emailFormRef.value.validateField(['email', 'captchaImage'])
    
    try {
      console.log('发送邮箱验证码请求:', {
        email: emailForm.email,
        captcha: emailForm.captchaImage,
        uuid: emailUuid.value
      })
      
      // 发送邮箱验证码
      const res = await getEmailCode({
        email: emailForm.email,
        captcha: emailForm.captchaImage,
        uuid: emailUuid.value
      })
      
      console.log('邮箱验证码发送成功:', res)
      
      // 保存邮箱验证码UUID
      emailCodeUuid.value = res.data.uuid || ''
      console.log('邮箱验证码UUID:', emailCodeUuid.value)
      
      // 开始倒计时
      emailCodeTimer.value = 60
      emailTimerInterval = setInterval(() => {
        emailCodeTimer.value--
        if (emailCodeTimer.value <= 0) {
          clearInterval(emailTimerInterval)
        }
      }, 1000)
      
      ElMessage.success('验证码已发送，请注意查收')
    } catch (error) {
      console.error('验证码发送失败', error.response || error)
      ElMessage.error(error.message || '图形验证码错误或发送失败，请重试')
      refreshEmailCaptcha()
    }
  } catch (error) {
    console.error(error)
  }
}

// 账号密码登录
const handleAccountLogin = async () => {
  if (loading.value) return
  
  try {
    // 表单验证
    await accountFormRef.value.validate()
    
    loading.value = true
    
    console.log('账号密码登录请求:', {
      userName: accountForm.userName,
      password: accountForm.password,
      captcha: accountForm.captcha,
      uuid: accountUuid.value
    })
    
    // 调用登录接口
    const res = await loginByUsername({
      userName: accountForm.userName,
      password: accountForm.password,
      captcha: accountForm.captcha,
      uuid: accountUuid.value
    })
    
    console.log('登录成功:', res)
    
    // 保存token
    userStore.setToken(res.data)
    
    // 保存用户信息
    userStore.setUserInfo({
      uid: res.data.uid || '10001',
      userId: res.data.userId || 'user_' + Date.now(),
      userName: accountForm.userName,
      userType: res.data.userType || '0',
      isAdmin: res.data.isAdmin || false
    })
    
    ElMessage.success('登录成功')
    
    // 跳转到首页或者重定向页面
    const redirect = route.query.redirect || '/dashboard'
    router.push(redirect)
  } catch (error) {
    console.error('登录失败', error.response || error)
    ElMessage.error(error.message || '登录失败，请重试')
    // 刷新验证码
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

// 手机号登录
const handlePhoneLogin = async () => {
  if (loading.value) return
  
  try {
    // 表单验证
    await phoneFormRef.value.validate()
    
    loading.value = true
    
    console.log('手机号登录请求:', {
      phoneNumber: phoneForm.phoneNumber,
      captcha: phoneForm.captcha,
      uuid: smsUuid.value
    })
    
    // 调用登录接口
    const res = await loginByPhone({
      phoneNumber: phoneForm.phoneNumber,
      captcha: phoneForm.captcha,
      uuid: smsUuid.value // 使用短信验证码的UUID
    })
    
    console.log('登录成功:', res)
    
    // 保存token
    userStore.setToken(res.data)
    
    // 保存用户信息
    userStore.setUserInfo({
      uid: res.data.uid || '10002',
      userId: res.data.userId || 'user_' + Date.now(),
      phoneNumber: phoneForm.phoneNumber,
      userType: res.data.userType || '0',
      isAdmin: res.data.isAdmin || false
    })
    
    ElMessage.success('登录成功')
    
    // 跳转到首页或者重定向页面
    const redirect = route.query.redirect || '/dashboard'
    router.push(redirect)
  } catch (error) {
    console.error('登录失败', error.response || error)
    ElMessage.error(error.message || '登录失败，请重试')
    // 刷新验证码
    refreshPhoneCaptcha()
  } finally {
    loading.value = false
  }
}

// 邮箱登录
const handleEmailLogin = async () => {
  if (loading.value) return
  
  try {
    // 表单验证
    await emailFormRef.value.validate()
    
    loading.value = true
    
    console.log('邮箱登录请求:', {
      email: emailForm.email,
      captcha: emailForm.captcha,
      uuid: emailCodeUuid.value
    })
    
    // 调用登录接口
    const res = await loginByEmail({
      email: emailForm.email,
      captcha: emailForm.captcha,
      uuid: emailCodeUuid.value // 使用邮箱验证码的UUID
    })
    
    console.log('登录成功:', res)
    
    // 保存token
    userStore.setToken(res.data)
    
    // 保存用户信息
    userStore.setUserInfo({
      uid: res.data.uid || '10003',
      userId: res.data.userId || 'user_' + Date.now(),
      email: emailForm.email,
      userType: res.data.userType || '0',
      isAdmin: res.data.isAdmin || false
    })
    
    ElMessage.success('登录成功')
    
    // 跳转到首页或者重定向页面
    const redirect = route.query.redirect || '/dashboard'
    router.push(redirect)
  } catch (error) {
    console.error('登录失败', error.response || error)
    ElMessage.error(error.message || '登录失败，请重试')
    // 刷新验证码
    refreshEmailCaptcha()
  } finally {
    loading.value = false
  }
}

// 监听选项卡切换，加载对应的验证码
const handleTabChange = (tab) => {
  if (tab === 'account' && !captchaUrl.value) {
    refreshCaptcha()
  } else if (tab === 'phone' && !phoneCaptchaUrl.value) {
    refreshPhoneCaptcha()
  } else if (tab === 'email' && !emailCaptchaUrl.value) {
    refreshEmailCaptcha()
  }
}

// 监听选项卡变化
watch(activeTab, (newTab) => {
  handleTabChange(newTab)
})

// 组件挂载时刷新验证码
onMounted(() => {
  console.log('登录页面加载，获取验证码')
  refreshCaptcha()
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (smsTimerInterval) clearInterval(smsTimerInterval)
  if (emailTimerInterval) clearInterval(emailTimerInterval)
})
</script>

<style scoped>
/* 样式已在全局CSS中定义 */
</style> 